package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.TestPaper;
import com.example.demo.entity.User;
import com.example.demo.service.TestPaperService;
import com.example.demo.service.UserService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test-paper")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class TestPaperController {

    @Autowired
    private TestPaperService testPaperService;
    
    @Autowired
    private UserService userService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 创建试卷（带tokens信息）
     * @param request 请求参数，包含用户ID、主题、题目详情、总tokens
     * @return 创建的试卷信息
     */
    @PostMapping("/create")
    public Result createTestPaper(@RequestBody Map<String, Object> request) {
        try {
            Integer userId = (Integer) request.get("userId");
            String topic = (String) request.get("topic");
            String titleDetailsJson = (String) request.get("titleDetails");
            Integer totalTokens = (Integer) request.get("totalTokens");

            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            TestPaper testPaper = new TestPaper();
            testPaper.setUserId(userId);
            testPaper.setTopic(topic);  // 设置试卷主题
            testPaper.setTitleDetails(titleDetailsJson);
            testPaper.setTotalTokens(totalTokens);

            // 保存试卷
            testPaperService.save(testPaper);
            
            // 扣除用户的token
            deductUserTokens(userId, totalTokens);

            Map<String, Object> result = new HashMap<>();
            result.put("tesrId", testPaper.getTesrId());
            result.put("userId", testPaper.getUserId());
            result.put("topic", testPaper.getTopic());
            result.put("createdAt", testPaper.getCreatedAt());

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建试卷失败: " + e.getMessage());
        }
    }

    /**
     * 提交试卷
     * @param request 请求参数，包含试卷ID和用户答案
     * @return 提交结果
     */
    @PostMapping("/submit")
    public Result submitTest(@RequestBody Map<String, Object> request) {
        try {
            System.out.println("收到提交试卷请求: " + request);
            
            // 获取参数 - 支持多种类型转换
            Object paperIdObj = request.get("paperId");
            Object userIdObj = request.get("userId");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> userAnswers = (List<Map<String, Object>>) request.get("answers");

            // 转换paperId
            Long paperId = null;
            if (paperIdObj != null) {
                if (paperIdObj instanceof Integer) {
                    paperId = ((Integer) paperIdObj).longValue();
                } else if (paperIdObj instanceof Long) {
                    paperId = (Long) paperIdObj;
                } else if (paperIdObj instanceof Number) {
                    paperId = ((Number) paperIdObj).longValue();
                }
            }
            
            // 转换userId
            Integer userId = null;
            if (userIdObj != null) {
                if (userIdObj instanceof Integer) {
                    userId = (Integer) userIdObj;
                } else if (userIdObj instanceof Number) {
                    userId = ((Number) userIdObj).intValue();
                }
            }

            System.out.println("解析参数 - paperId: " + paperId + ", userId: " + userId);
            System.out.println("用户答案数量: " + (userAnswers != null ? userAnswers.size() : 0));

            if (paperId == null || userId == null) {
                System.out.println("参数验证失败: paperId=" + paperId + ", userId=" + userId);
                return Result.error("试卷ID和用户ID不能为空");
            }

            // 查询试卷
            TestPaper testPaper = testPaperService.getById(paperId);
            System.out.println("查询到的试卷: " + testPaper);
            
            if (testPaper == null) {
                System.out.println("试卷不存在, paperId: " + paperId);
                return Result.error("试卷不存在");
            }

            // 验证用户ID
            System.out.println("试卷所属用户ID: " + testPaper.getUserId() + ", 请求用户ID: " + userId);
            if (!testPaper.getUserId().equals(userId)) {
                System.out.println("用户ID不匹配");
                return Result.error("无权访问此试卷");
            }

            // 解析现有的题目详情JSON
            String titleDetailsJson = testPaper.getTitleDetails();
            System.out.println("题目详情JSON长度: " + (titleDetailsJson != null ? titleDetailsJson.length() : 0));
            
            if (titleDetailsJson == null || titleDetailsJson.isEmpty()) {
                System.out.println("题目详情为空");
                return Result.error("试卷题目详情为空");
            }
            
            List<Map<String, Object>> questions;
            try {
                questions = parseJsonToQuestionList(titleDetailsJson);
                System.out.println("解析到题目数量: " + questions.size());
            } catch (Exception e) {
                System.out.println("解析题目详情失败: " + e.getMessage());
                e.printStackTrace();
                return Result.error("解析题目详情失败: " + e.getMessage());
            }

            // 更新用户答案到题目中
            if (userAnswers != null && !userAnswers.isEmpty()) {
                for (Map<String, Object> answer : userAnswers) {
                    Object questionIdObj = answer.get("questionId");
                    Object userAnswerObj = answer.get("userAnswer");
                    
                    System.out.println("处理答案 - questionId: " + questionIdObj + ", userAnswer: " + userAnswerObj);
                    
                    if (questionIdObj != null && userAnswerObj != null) {
                        // 将questionId转换为整数
                        Integer questionId = null;
                        if (questionIdObj instanceof Integer) {
                            questionId = (Integer) questionIdObj;
                        } else if (questionIdObj instanceof Number) {
                            questionId = ((Number) questionIdObj).intValue();
                        }
                        
                        String userAnswer = userAnswerObj.toString();

                        if (questionId != null && userAnswer != null) {
                            // 找到对应的题目并更新用户答案
                            for (Map<String, Object> question : questions) {
                                Object idObj = question.get("id");
                                if (idObj != null) {
                                    Integer id = null;
                                    if (idObj instanceof Integer) {
                                        id = (Integer) idObj;
                                    } else if (idObj instanceof Number) {
                                        id = ((Number) idObj).intValue();
                                    }
                                    
                                    if (id != null && id.equals(questionId)) {
                                        question.put("useranswer", userAnswer);
                                        System.out.println("更新题目 " + questionId + " 的答案为: " + userAnswer);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 将更新后的题目列表转换为JSON字符串
            String updatedJson = convertQuestionListToJson(questions);
            System.out.println("更新后的JSON: " + updatedJson);

            // 更新试卷
            testPaper.setTitleDetails(updatedJson);
            
            // 计算正确率
            int totalQuestions = questions.size();
            int correctAnswers = 0;
            for (Map<String, Object> question : questions) {
                Object userAnswerObj = question.get("useranswer");
                // 尝试多种可能的字段名
                Object correctAnswerObj = question.get("correctanswer");
                if (correctAnswerObj == null) {
                    correctAnswerObj = question.get("correct_answer");
                }
                if (correctAnswerObj == null) {
                    correctAnswerObj = question.get("correctAnswer");
                }
                
                System.out.println("题目ID: " + question.get("id") + 
                    ", 用户答案: " + userAnswerObj + 
                    ", 正确答案: " + correctAnswerObj);
                
                if (userAnswerObj != null && correctAnswerObj != null) {
                    String userAnswer = userAnswerObj.toString().trim();
                    String correctAnswer = correctAnswerObj.toString().trim();
                    if (userAnswer.equalsIgnoreCase(correctAnswer)) {
                        correctAnswers++;
                        System.out.println("答案匹配！");
                    } else {
                        System.out.println("答案不匹配: " + userAnswer + " != " + correctAnswer);
                    }
                } else {
                    System.out.println("答案为空: userAnswer=" + userAnswerObj + ", correctAnswer=" + correctAnswerObj);
                }
            }
            
            double correctRate = totalQuestions > 0 ? (correctAnswers * 100.0 / totalQuestions) : 0.0;
            testPaper.setCorrectRate(correctRate);
            System.out.println("计算正确率: " + correctRate + "% (" + correctAnswers + "/" + totalQuestions + ")");
            
            // 调用AI API生成点评
            Integer aiTokens = 0;
            try {
                aiTokens = generateAIComment(updatedJson, testPaper);
                System.out.println("AI点评生成成功，消耗tokens: " + aiTokens);
                
                // 累加tokens到total_tokens
                Integer currentTokens = testPaper.getTotalTokens() != null ? testPaper.getTotalTokens() : 0;
                testPaper.setTotalTokens(currentTokens + (aiTokens != null ? aiTokens : 0));
                System.out.println("更新total_tokens: " + testPaper.getTotalTokens());
            } catch (Exception e) {
                System.out.println("AI点评生成失败: " + e.getMessage());
                e.printStackTrace();
                // 即使AI生成失败，也继续保存试卷
                testPaper.setAiComments(null);
            }
            
            boolean updateResult = testPaperService.updateById(testPaper);
            System.out.println("数据库更新结果: " + updateResult);
            
            // 扣除用户用于AI点评的tokens
            if (aiTokens != null && aiTokens > 0) {
                deductUserTokens(userId, aiTokens);
            }

            return Result.success("试卷提交成功");
        } catch (Exception e) {
            System.out.println("提交试卷异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("提交试卷失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的试卷列表
     * @param userId 用户ID
     * @return 试卷列表
     */
    @GetMapping("/list/{userId}")
    public Result getTestPaperList(@PathVariable Integer userId) {
        try {
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            // 使用MyBatis-Plus查询该用户的所有试卷
            List<TestPaper> testPapers = testPaperService.lambdaQuery()
                    .eq(TestPaper::getUserId, userId)
                    .orderByDesc(TestPaper::getCreatedAt)
                    .list();

            // 转换为简略信息
            List<Map<String, Object>> resultList = testPapers.stream().map(paper -> {
                Map<String, Object> paperInfo = new HashMap<>();
                paperInfo.put("tesrId", paper.getTesrId());
                paperInfo.put("topic", paper.getTopic());
                paperInfo.put("createdAt", paper.getCreatedAt());
                paperInfo.put("totalTokens", paper.getTotalTokens());
                paperInfo.put("correctRate", paper.getCorrectRate());
                return paperInfo;
            }).toList();

            Map<String, Object> result = new HashMap<>();
            result.put("list", resultList);
            result.put("total", resultList.size());

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取试卷列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取试卷详情
     * @param paperId 试卷ID
     * @return 试卷详情
     */
    @GetMapping("/{paperId}")
    public Result getTestPaper(@PathVariable Long paperId) {
        try {
            TestPaper testPaper = testPaperService.getById(paperId);
            if (testPaper == null) {
                return Result.error("试卷不存在");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("tesrId", testPaper.getTesrId());
            result.put("userId", testPaper.getUserId());
            result.put("topic", testPaper.getTopic());
            result.put("totalTokens", testPaper.getTotalTokens());
            result.put("aiComments", testPaper.getAiComments());
            result.put("correctRate", testPaper.getCorrectRate());
            result.put("createdAt", testPaper.getCreatedAt());

            // 解析题目详情
            if (testPaper.getTitleDetails() != null && !testPaper.getTitleDetails().isEmpty()) {
                try {
                    List<Map<String, Object>> questions = parseJsonToQuestionList(testPaper.getTitleDetails());
                    result.put("questions", questions);
                } catch (Exception e) {
                    return Result.error("解析题目详情失败: " + e.getMessage());
                }
            }

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取试卷失败: " + e.getMessage());
        }
    }

    /**
     * 解析JSON字符串为题目列表
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> parseJsonToQuestionList(String json) {
        try {
            // 使用ObjectMapper解析JSON字符串为List<Map<String, Object>>
            TypeReference<List<Map<String, Object>>> typeRef = new TypeReference<List<Map<String, Object>>>() {};
            return objectMapper.readValue(json, typeRef);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    /**
     * 将题目列表转换为JSON字符串
     */
    private String convertQuestionListToJson(List<Map<String, Object>> questions) {
        try {
            // 使用ObjectMapper将List转换为JSON字符串
            return objectMapper.writeValueAsString(questions);
        } catch (Exception e) {
            throw new RuntimeException("JSON序列化失败", e);
        }
    }

    /**
     * 调用AI API生成点评，返回消耗的tokens数量
     * @param questionsJson 题目JSON
     * @param testPaper 试卷对象
     * @return 消耗的total_tokens
     */
    private Integer generateAIComment(String questionsJson, TestPaper testPaper) throws Exception {
        String apiUrl = "https://api.siliconflow.cn/v1/chat/completions";
        String apiKey = "Bearer sk-xnylbjmikgqzebwiljarthzyvyumjroagltlioeauesinnsn";

        // 构建请求体
        String systemPrompt = "请基于以下答题数据生成一段连续的分析话术，直接开始总结表现，避免使用\"根据你提供的答题数据\"或\"具体如下\"等开头。要求话术自然连贯，涵盖以下要点： 1. 总体评价。 2. 答对题目的知识点亮点 3. 答错题目的具体分析 4. 整体学习建议（如加强概念辨析、流程记忆）。 话术需以段落形式组织，逻辑顺畅，如同教师当面点评。5.话术150字左右。";
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-ai/DeepSeek-V3.2-Exp");
        
        List<Map<String, Object>> messages = List.of(
            Map.of("role", "system", "content", systemPrompt),
            Map.of("role", "user", "content", questionsJson)
        );
        requestBody.put("messages", messages);
        requestBody.put("stream", false);
        requestBody.put("max_tokens", 3000);
        
        String jsonBody = objectMapper.writeValueAsString(requestBody);

        // 发送HTTP请求
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", apiKey);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // 写入请求体
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取响应
        int responseCode = connection.getResponseCode();
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                responseCode >= 200 && responseCode < 300 
                    ? connection.getInputStream() 
                    : connection.getErrorStream(),
                StandardCharsets.UTF_8
            )
        );

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        if (responseCode >= 200 && responseCode < 300) {
            // 解析响应JSON
            Map<String, Object> responseMap = objectMapper.readValue(response.toString(), 
                new TypeReference<Map<String, Object>>() {});
            
            // 提取usage信息中的total_tokens
            Integer totalTokens = null;
            if (responseMap.containsKey("usage")) {
                @SuppressWarnings("unchecked")
                Map<String, Object> usage = (Map<String, Object>) responseMap.get("usage");
                if (usage != null && usage.containsKey("total_tokens")) {
                    Object tokensObj = usage.get("total_tokens");
                    if (tokensObj instanceof Number) {
                        totalTokens = ((Number) tokensObj).intValue();
                    }
                }
            }
            
            // 设置AI评论内容
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
            if (choices != null && !choices.isEmpty()) {
                @SuppressWarnings("unchecked")
                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                if (message != null) {
                    String content = (String) message.get("content");
                    if (content != null) {
                        testPaper.setAiComments(content);
                    }
                }
            }
            
            System.out.println("AI API返回total_tokens: " + totalTokens);
            return totalTokens;
        } else {
            throw new Exception("AI API请求失败，状态码: " + responseCode + ", 响应: " + response.toString());
        }
    }
    
    /**
     * 扣除用户的token
     * @param userId 用户ID
     * @param tokensToDeduct 需要扣除的token数量
     */
    private void deductUserTokens(Integer userId, Integer tokensToDeduct) {
        try {
            if (userId == null || tokensToDeduct == null || tokensToDeduct <= 0) {
                System.out.println("参数无效，不扣除tokens: userId=" + userId + ", tokens=" + tokensToDeduct);
                return;
            }
            
            // 查询用户信息
            User user = userService.getById(userId.longValue());
            if (user == null) {
                System.err.println("用户不存在，无法扣除tokens: userId=" + userId);
                return;
            }
            
            // 检查是否为无限制token
            if (user.getTotalTokens() != null && user.getTotalTokens() == -1) {
                System.out.println("用户拥有无限制token，不扣除: userId=" + userId);
                return;
            }
            
            // 获取当前token数量
            Integer currentTokens = user.getTotalTokens() != null ? user.getTotalTokens() : 0;
            
            // 计算新的token数量
            Integer newTokens = Math.max(0, currentTokens - tokensToDeduct);
            
            // 更新用户的token数量
            user.setTotalTokens(newTokens);
            boolean updateResult = userService.updateById(user);
            
            if (updateResult) {
                System.out.println("成功扣除用户tokens: userId=" + userId + 
                    ", 扣除前=" + currentTokens + ", 扣除=" + tokensToDeduct + ", 扣除后=" + newTokens);
            } else {
                System.err.println("扣除用户tokens失败: userId=" + userId);
            }
        } catch (Exception e) {
            System.err.println("扣除用户tokens异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
